import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
import commonLayout from '@/views/common'

/**
 *
 * @param  {Array} userRouter 后台返回的用户权限json
 * @param  {Array} allRouter  前端配置好的所有动态路由的集合
 * @return {Array} realRoutes 过滤后的路由
 */

export function filterAsyncRoutes(allRouter = [], userRouter = []) {
  var realRoutes = []
  userRouter.map(v => {
    // eslint-disable-next-line eqeqeq
    v.path = v.level == 1 ? '/' + v.menuCode : v.menuCode
    v.name = v.url
    // eslint-disable-next-line eqeqeq
    v.component = v.level == 1 ? Layout : commonLayout
    v.meta = {
      title: v.title, titleEn: v.titleEn, icon: v.menuIcon
    }
    allRouter.map(item => {
      if (v.url && item.name) {
        if (v.url === item.name) {
          v.name = v.url
          v.path = item.path
          v.meta = {
            title: v.title, titleEn: v.titleEn, icon: v.menuIcon, noCache: true
          }
          v.component = item.component
        }
      }
    })
    filterAsyncRoutes(asyncRoutes, v.children)
    realRoutes.push(v)
  })
  
  return realRoutes
}

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    selectLevel1Menu: ''
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_SELECTLEVEL1MENU: (state, selectLevel1Menu) => {
      state.selectLevel1Menu = selectLevel1Menu
      console.log('selectLevel1Menu = ' + selectLevel1Menu)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        console.log('Do GenerateRoutes')
        // // 使用权限
        // var isDash = false
        // for (var j = 0; j < data.length; j++) {
        //   if (data[j].url === 'Dashboard') {
        //     isDash = true
        //   }
        // }
        // var accessedRoutes = []
        // if (isDash) {
        //   accessedRoutes = dashboardRoutes.concat(filterAsyncRoutes(asyncRoutes, data))
        // } else {
        //   accessedRoutes = filterAsyncRoutes(asyncRoutes, data)
        // }
        var accessedRoutes = filterAsyncRoutes(asyncRoutes, data)
        console.log('Do GenerateRoutes filter data = {} ', data)
        console.log('Do GenerateRoutes filter asyncRoutes = {} ', asyncRoutes)
        console.log('Do GenerateRoutes filter accessedRoutes = {} ', accessedRoutes)
        const accessedRoutesEnd = accessedRoutes
        commit('SET_ROUTES', accessedRoutesEnd)
        resolve(accessedRoutes)

        // 不使用权限
        // commit('SET_ROUTES', asyncRoutes)
        // resolve(asyncRoutes)
      })
    },
    SelectLevel1Menu({ commit }, data) {
      commit('SET_SELECTLEVEL1MENU', data)
    }
  }
}

export default permission
